<?php
App::uses('AppController', 'Controller');

class ReportsController extends AppController {
    
    
    public function debts() {
        $filter = @$this->data['Filter'];
        
        $this->loadModel('Client');
        $clients = $this->Client->find('list');
        
        if (!empty($filter['start']) && !empty($filter['end'])) {
            $clientId = @$filter['client_id'];
            $start    = $filter['start'];
            $end      = $filter['end'];
            
            if ($clientId) {
                $c = array($this->Client->findById($clientId, array('Client.*')));
            } else {
                $c = $this->Client->find('all', array('fields'=>array('Client.*'), 'order'=>'Client.name'));
            }
            
            $data = array();
            $this->loadModel('Invoice');
            $this->loadModel('Payment');
            
            foreach ($c as $client) {
                $clientId   = $client['Client']['id'];
                
                $data[$clientId] = array(
                    'start_due' => (float)$client['Client']['start_due'],
                    'invoiced'  => 0,
                    'payed'     => 0
                );
                
                $invoices = $this->Invoice->getClientInvoices($clientId, $start, $end);
                $amounts = Set::extract('{n}.Invoice.amount', $invoices);
                $amounts = $amounts ? $amounts : array();
                $data[$clientId]['invoiced'] = array_sum($amounts);
                
                $exch_rates = array();
                foreach ($invoices as $invoice) {
                    $exch_rates[$invoice['Invoice']['id']] = (float)$invoice['ExchangeRate']['rate'];
                }
                
                $campaignIds = Set::extract('{n}.Campaign.id', $invoices);
                $payments = $this->Payment->getCampaignsPayments($campaignIds);
                foreach ($payments as $payment) {
                    $invoiceId = (int)@$payment['Invoice']['id'];
                    $data[$clientId]['payed'] += $payment['Payment']['amount'] * $exch_rates[$invoiceId];
                }
            }
        }
        
        $this->set(compact('clients', 'data', 'filter'));
    }

    public function debt_details($clientId, $start, $end) {
        if ($this->isAjax()) {
            $this->layout = 'ajax';
        }
        
        $this->loadModel('Client');
        $client = $this->Client->findById($clientId);
        
        $this->loadModel('Invoice');
        $invoices = $this->Invoice->getClientInvoices($clientId, $start, $end);
        
        $this->loadModel('Payment');
        $campaignIds = Set::extract('{n}.Campaign.id', $invoices);
        $payments = array();
        foreach( $this->Payment->getCampaignsPayments($campaignIds) as $payment) {
            $invoiceId = $payment['Invoice']['id'];            
            if (empty($payments[$invoiceId])) {
                $payments[$invoiceId] = array();
            }
            $payments[$invoiceId][] = $payment;
        }
        $this->set(compact('invoices', 'payments', 'client', 'start', 'end'));
    }
    
    public function location_occupation() {
        $filter = @$this->data['Filter'];
        
        $this->loadModel('Location');
        $locations = $this->Location->find('list');
        
        $data = array(
            'reserved' => array(),
            'occupied' => array()
        );
        
        $print = false;
        if (!empty($filter['start']) && !empty($filter['end'])) {
            $print = $filter['print'];
            
            // search for reservations
            $reservations = $this->Location->LocationReservation->find('all', array(
                'fields'     => 'LocationReservation.*',
                'recursive'  => 0,
                'conditions' => array(
                    'location_id' => $filter['location_id'],
                    array(
                        "OR" => array(
                            array(
                                'start >=' => $filter['start'],
                                'start <=' => $filter['end']
                            ),
                            array(
                                'end >=' => $filter['start'],
                                'end <=' => $filter['end']
                            )
                        )
                    )
                )
            ));
            foreach ($reservations as $r) {
                $start = totime($r['LocationReservation']['start']);
                $end   = totime($r['LocationReservation']['end']);
                
                for ($i=$start; $i<=$end; $i+=60*60*24) {
                    $data['reserved'][$i] = $r['LocationReservation'];
                }
            }
            
            // search for campaigns
            $this->loadModel('CampaignsLocation');
            $campaigns = $this->CampaignsLocation->find('all', array(
                'fields'     => 'CampaignsLocation.*',
                'recursive'  => 0,
                'conditions' => array(
                    'location_id' => $filter['location_id'],
                    array(
                        "OR" => array(
                            array(
                                'start >=' => $filter['start'],
                                'start <=' => $filter['end']
                            ),
                            array(
                                'end >=' => $filter['start'],
                                'end <=' => $filter['end']
                            ),
                        )
                    )
                )
            ));
            foreach ($campaigns as $c) {
                $start = totime($c['CampaignsLocation']['start']);
                $end   = totime($c['CampaignsLocation']['end']);
                
                for ($i=$start; $i<=$end; $i+=60*60*24) {
                    $data['occupied'][$i] = $c['CampaignsLocation'];
                }
            }
        }
        
        $this->set(compact('locations', 'data', 'filter'));
        
        if ($print) {
            $this->layout = 'blank';
            return $this->render($this->action . "_print");
        }
    }
}
